package com.fengyi.library.controller;

import com.fengyi.library.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Zipkin链路跟踪演示控制器
 * 用于展示分布式调用链路跟踪功能
 */
@RestController
@RequestMapping("/api/tracing")
@Slf4j
public class ZipkinTracingController {

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private BookService bookService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 简单调用示例
     * @return 服务信息
     */
    @GetMapping("/simple")
    public Map<String, Object> simpleTrace() {
        log.info("进入simpleTrace方法，当前端口: {}", serverPort);
        
        Map<String, Object> result = new HashMap<>();
        result.put("service", "Library Service");
        result.put("port", serverPort);
        result.put("timestamp", System.currentTimeMillis());
        result.put("tracing", "Zipkin简单调用示例");
        
        log.info("simpleTrace方法返回结果: {}", result);
        return result;
    }
    
    /**
     * 复杂链路调用示例，模拟多服务调用
     * @param delay 人为延迟(毫秒)，用于测试耗时
     * @return 调用结果
     */
    @GetMapping("/complex")
    public Map<String, Object> complexTrace(
            @RequestParam(required = false, defaultValue = "0") int delay) {
        
        log.info("进入complexTrace方法，当前端口: {}, 延迟: {}ms", serverPort, delay);
        
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        
        // 步骤1: 模拟业务处理延迟
        if (delay > 0) {
            try {
                log.info("模拟业务处理延迟{}ms", delay);
                TimeUnit.MILLISECONDS.sleep(delay);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        
        // 步骤2: 调用图书服务
        log.info("调用图书服务");
        var bookCount = bookService.countBooks();
        
        // 步骤3: 调用服务信息API
        log.info("调用服务信息API");
        ResponseEntity<Map> serviceInfoResponse = restTemplate.getForEntity(
            "http://cloud-library-service/api/service-info", Map.class);
        
        // 构建结果
        Map<String, Object> result = new HashMap<>();
        result.put("service", "Library Tracing Service");
        result.put("port", serverPort);
        result.put("bookCount", bookCount);
        result.put("serviceInfo", serviceInfoResponse.getBody());
        result.put("processingTime", System.currentTimeMillis() - startTime);
        result.put("timestamp", System.currentTimeMillis());
        
        log.info("complexTrace方法执行完成，耗时: {}ms", System.currentTimeMillis() - startTime);
        return result;
    }
    
    /**
     * 异常调用示例，模拟链路中出现异常
     * @return 调用结果
     */
    @GetMapping("/error")
    public Map<String, Object> errorTrace() {
        log.info("进入errorTrace方法，当前端口: {}", serverPort);
        
        Map<String, Object> result = new HashMap<>();
        result.put("service", "Library Service");
        result.put("port", serverPort);
        
        try {
            // 模拟50%概率发生异常
            if (System.currentTimeMillis() % 2 == 0) {
                log.error("模拟业务异常");
                throw new RuntimeException("模拟的业务异常，用于测试链路跟踪");
            }
            
            result.put("status", "success");
            result.put("message", "调用成功，没有发生异常");
        } catch (Exception e) {
            log.error("调用异常: {}", e.getMessage(), e);
            result.put("status", "error");
            result.put("error", e.getMessage());
        }
        
        log.info("errorTrace方法返回结果: {}", result);
        return result;
    }
} 